<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/18 0018
 * Time: 18:00
 */

namespace app\admin\controller;


use phpDocumentor\Reflection\DocBlock;
use think\Db;
use app\admin\model\Member;
use app\admin\model\AppleOrder;
use OSS\OssClient;
use OSS\Core\OssException;

class News extends Base
{
    public function lists()
    {

        if(isset($this->_param['op'])&&$this->_param['op']=='table'){
        $list = db('news')->order('id desc');
        $list->limit(($this->_param['page']-1)*$this->_param['limit'],$this->_param['limit']);
        $data = $list->select();
        foreach ($data as $k=>$v){
            $data[$k]['create_time'] = date("Y-m-d H:i:s", $data[$k]['create_time']);
            $data[$k]['is_hot_str']  = $data[$k]['is_hot'] ? '首页推荐' : '未推荐';
        }
        $this->assign('map', $this->_param);
        $total = $list->count();
        $this->ajaxReturn('',$data,$total);
    }
        if(!isset($this->_param['op'])){
            return $this->fetch();
        }
    }


    /**
     * 添加和编辑新闻操作
     */
    public function add($id = 0)
    {
        $id = isset($this->_param['id']) ? $this->_param['id'] : '';
        if ($this->request->isPost()) {
//            print_r($_FILES);print_r($this->_param);die;
            if (empty($id)) {
                $this->_param['img_src'] = isset($_FILES['img_src']) ? $_FILES['img_src'] : '';
                $rule = [
                    ['title', 'require', '主标题不能为空'],
                    ['img_src', 'require', '图片不能为空'],
                    ['content', 'require', '内容不能为空'],
                ];
            } else {
                $rule = [
                    ['title', 'require', '主标题不能为空'],
                    ['content', 'require', '内容不能为空'],
                ];
            }
            $msg = $this->validate($this->_param, $rule);
            if ($msg !== true) {
                $this->error($msg, '');
            }
            if (!empty($_FILES['img_src']['name'])){
                $type_name = 'news';
                $banner_dir = isset($banner_dir) ? $banner_dir : $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $type_name;
                if (!file_exists($banner_dir)) mkdirs($banner_dir);
                $file = $_FILES['img_src'];
                $tmp_file = $file ['tmp_name'];
                $file_types = explode(".", $file['name']);
                $file_type = $file_types [count($file_types) - 1];
                $file_names = $type_name . '' . time() . '.' . $file_type;
                $file_name = $banner_dir . '/' . $file_names;
                if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg', 'jpeg'))) {
                    $this->error('不是要求图片文件，请重新选择！', '');
                }
                if (copy($file['tmp_name'], $file_name)) {

                    //上传阿里云OSS
                    if(true)
                    {
                        $root = $_SERVER['DOCUMENT_ROOT'];
                        if (is_file($root . '/../extend/oss/autoload.php')) {
                            require_once $root . '/../extend/oss/autoload.php';
                        }
                        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
                        try {
                            $ossClient->uploadFile($this->bucket, 'uploads/news/'.$file_names, $file_name);
                            unlink($file_name);
                        } catch (OssException $e) {
                            printf($e->getMessage() . "\n");
                            return;
                        }
                    }

                    $this->_param['img_src'] = $file_names;
                    if (empty($id)) {
                        $this->_param['create_time'] = time();
                        Db::name('news')->insert($this->_param);
                        $this->success('保存成功',url('news/lists'));
                    } else {
                        Db::name('news')->where('id', $id)->update($this->_param);
                        $this->success('保存成功',url('news/lists'));
                    }
                } else {
                    $this->error('图片上传失败',url('news/lists'));
                }
            } else {
                if (!empty($id)) {
                    Db::name('news')->where('id', $id)->update($this->_param);
                    $this->success('保存成功',url('news/lists'));
                   // $this->ajaxReturn('编辑成功','','',200);
                }
                Db::name('news')->insert($this->_param);
                $this->success('保存成功',url('news/lists'));
            }


        } else {
            if (!empty($id)) {
                $data = Db::name('news')->where(['id' => $id])->find();
                $url=$this->url;
                $data['img_src']=$url . '/uploads/news/' . $data['img_src'];
                $this->assign('data', $data);
            }
            return $this->fetch('edit');
        }
    }
    /**
     * 删除新闻
     */
    public function del($id = 0)
    {
        Db::name('news')->where('id', $id)->delete();
        $this->ajaxReturn('刪除成功','','',0);
    }

    //是否设置为热门
    public function is_hot()
    {
        $id = $this->_param['id'];
        if (isset($this->_param['cancle'])) {
            $res = DB::name('news')->where('id', $id)->update(['is_hot' => 0]);
            $this->ajaxReturn('取消成功', '', '', '200');
        } else {
            $res = DB::name('news')->where('id', $id)->update(['is_hot' => 1]);
            $this->ajaxReturn('置顶成功', '', '', '200');
        }
    }
}